package com.share51.novel.config.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;

/**
 * http 爬虫工具配置
 * @author gb
 */
@Slf4j
@Configuration
public class HttpClientConfig {

    private CloseableHttpClient httpClient;
    private final static Object SYNC_LOCK = new Object();



    private PoolingHttpClientConnectionManager manager(String hostname,int port){
        //用于创建普通（未加密）套接字的默认类
        ConnectionSocketFactory connectionSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
        //创建加密的套接字
        LayeredConnectionSocketFactory layeredConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();

        Registry<ConnectionSocketFactory> registry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", connectionSocketFactory)
                .register("https",layeredConnectionSocketFactory)
                .build();

        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager
                = new PoolingHttpClientConnectionManager(registry);
        // 最大连接数
        poolingHttpClientConnectionManager.setMaxTotal(20);
        // 路由最大连接数
        //路由:包含的数据有目标主机、本地地址、代理链、是否tunnulled、是否layered、是否是安全路由
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10);

        HttpHost httpHost = new HttpHost(hostname, port);
        // 某个站点或者某个ip的最大连接个数
        poolingHttpClientConnectionManager.setMaxPerRoute(new HttpRoute(httpHost),10);
        return poolingHttpClientConnectionManager;
    }

    public CloseableHttpClient getHttpClient(String url){
        String hostname = url.split("/")[2];
        int port = 80;
        if (hostname.contains(":")) {
            String[] arr = hostname.split(":");
            hostname = arr[0];
            port = Integer.parseInt(arr[1]);
        }
        // 双重校验锁
        if (httpClient == null) {
            synchronized (SYNC_LOCK) {
                if (httpClient == null) {
                    httpClient = createHttpClient(hostname, port);
                }
            }
        }
        return httpClient;
    }

    private CloseableHttpClient createHttpClient(String hostname, int port) {
       return HttpClients.custom()
                .setConnectionManager(manager(hostname,port))
                .setRetryHandler(handler())
                .build();
    }

    private HttpRequestRetryHandler handler(){
        return (IOException e, int i, HttpContext httpContext)-> {
            if (i > 3){
                // 重试超过3次,放弃请求
                log.error("retry has more than 3 time, give up request");
                return false;
            }
            if (e instanceof NoHttpResponseException){
                //服务器没有响应,可能是服务器断开了连接,应该重试
                log.error("receive no response from server, retry");
                return true;
            }
            if (e instanceof SSLHandshakeException){
                // SSL握手异常
                log.error("SSL hand shake exception");
                return false;
            }
            if (e instanceof ConnectTimeoutException){
                // 连接超时
                log.error("Connection Time out");
                return false;
            }
            if (e instanceof InterruptedIOException){
                //超时
                log.error("InterruptedIOException");
                return false;
            }
            if (e instanceof UnknownHostException){
                // 服务器不可达
                log.error("server host unknown");
                return false;
            }

            if (e instanceof SSLException){
                log.error("SSLException");
                return false;
            }
            HttpClientContext context = HttpClientContext.adapt(httpContext);
            HttpRequest request = context.getRequest();
            return !(request instanceof HttpEntityEnclosingRequest);
        };
    }
}
